package Concurrency2.Chapter02_InnerLockPrinciple.P01_ProducerConsumer;

import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 生产者功能:
 * 1, 实现Runnable接口
 * 2, 保存一个Callable实例
 * 基本的功能模板
 */
public class Producer<T> implements Runnable {
    private Callable<T> action;
    private Integer PRODUCE_GAP = 1;
    private String name;
    private static final AtomicInteger producerNo = new AtomicInteger(1);
    private Integer timeOut;

    public Producer(Callable<T> action,Integer timeOut) {
        this.action = action;
        this.name = "ProducerNo: " + producerNo.getAndIncrement();
        this.timeOut = timeOut == null ? PRODUCE_GAP : timeOut;
    }

    /**
     * 实现创建产品, 将产品添加到DataBuffer中功能.
     * 功能: 每隔TIMEOUT秒, 生产一个产品到DataBuffer中.
     */
    @Override
    public void run() {
        while (true) {
            try {
                T result = action.call();
                TimeUnit.SECONDS.sleep(timeOut);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }
}
